package com.sangmo.fts.basic.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.session.UserInterface;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.basic.model.Company;
import com.sangmo.fts.basic.repo.CompanyRepo;
import com.sangmo.fts.common.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CompanyEntityService extends BaseViewService<Company> {

    @Autowired
    private CompanyRepo companyRepo;

    @Override
    protected IDataViewRepo<Company> getRepo() {
        return companyRepo;
    }

    @Override
    protected void onCreate(Company entity, Object bo) {
        super.onCreate(entity, bo);
        entity.setCode(RandomUtils.generateRandomStr(8));
    }

    @Override
    protected void onDelete(Company entity) {
        super.onDelete(entity);
        if (entity.isInternal()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.company.delete.permit.disabled");
        }
        Long currentUserId = (Long)UserSession.getUserInterface().getId();
        if (!entity.getCreatedBy().equals(currentUserId)) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.company.delete.notallowed");
        }
    }
}
